namespace eval log_on_open {
    custom::defvar options(max_messages) 20 \
	[::msgcat::mc "Maximum number of log messages to show in newly\
		       opened chat window (if set to negative then the\
		       number is unlimited)."] \
	-type integer -group Chat
    custom::defvar options(max_interval) 24 \
	[::msgcat::mc "Maximum interval length in hours for which log\
		       messages should be shown in newly opened chat\
		       window (if set to negative then the interval is\
		       unlimited)."] \
	-type integer -group Chat
}

proc log_on_open::show {chatid type} {
    variable options

    if {$type != "chat"} return

    set connid [chat::get_connid $chatid]
    set jid [chat::get_jid $chatid]
    set bare_jid [node_and_server_from_jid $jid]
    set gc [chat::is_groupchat [chat::chatid $connid $bare_jid]]

    if {!$gc} {
	set log_jid $bare_jid
    } else {
	set log_jid $jid
    }
    
    set messages [::logger::get_last_messages $log_jid $options(max_messages) \
					      $options(max_interval)]

    foreach msg $messages {
	array unset tmp
	if {[catch {array set tmp $msg}]} continue

	set x {}
	if {[info exists tmp(timestamp)]} {
	    set seconds [clock scan $tmp(timestamp) -gmt 1]
	    set date [clock format $seconds -format "%Y%m%dT%H:%M:%S" -gmt 1]
	    lappend x [jlib::wrapper:createtag x \
			   -vars [list xmlns "jabber:x:delay" \
				       stamp $date]]
	}
	if {[info exists tmp(jid)]} {
	    if {$tmp(jid) == ""} {
		# Synthesized message
		set from ""
	    } elseif {(!$gc && [node_and_server_from_jid $tmp(jid)] != $bare_jid) || \
		 $gc && $tmp(jid) != $jid} {
		set from [jlib::connection_jid $connid]
	    } else {
		set from $jid
	    }
	} else {
	    set from ""
	}
	# Don't log this message. Request this by creating very special 'empty'
	# tag which can't be received from the peer.
	# TODO: Create more elegant mechanism
	lappend x [jlib::wrapper:createtag "" \
		       -vars [list xmlns "tkabber:x:nolog"]]

	chat::add_message $chatid $from $type $tmp(body) $x
    }
}

hook::add open_chat_post_hook [namespace current]::log_on_open::show 100

# vim:ts=8:sw=4:sts=4:noet
